﻿using CloudDcPc.Entity;
using CloudDcPc.util;
using CloudDcPc.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace CloudDcPc
{
    /// <summary>
    /// Main.xaml 的交互逻辑
    /// </summary>
    public partial class Main : Window
    {
        private object obj = new object();

        private List<Order> list;
        private List<Tab> list_tab;
        private string print_tip;
        private List<int> list_tab_num;
        private int mTrue_tab_num;
        private string mTrue_tab_name;
        private string mNow_order_num;
        private string mUser_num;
        private int mStartIndex = 0;
        private int mPageNums = 20;
        private string mWhere_pre = "";
        private bool isAlert = false;

        private User user = null;
        private string order_id = "";
        public Main(string user_num)
        {
            mUser_num = user_num;
            InitializeComponent();

            list_tab_num = new List<int>();
            this.user = App.UserBean.GetUserByField("user_num", user_num);
            App.user = this.user;

            dp_start_time.Text = dp_end_time.Text= DateTime.Now.ToShortDateString();
             
            if (App.user.Type < 3)
            {
                if (Properties.Settings.Default.set_sy_power_time == 0)
                    col1_sp_col1_checkout_record.Visibility = Visibility.Collapsed;
                col1_sp_manage.Visibility = Visibility.Collapsed;
                dp_start_time.DisplayDateStart = DateTime.Now.AddDays(0 -Convert.ToDouble( Properties.Settings.Default.set_sy_power_time));
                dp_start_time.DisplayDateEnd = DateTime.Now;

                dp_end_time.DisplayDateStart = DateTime.Now.AddDays(0 - Convert.ToDouble(Properties.Settings.Default.set_sy_power_time));
                dp_end_time.DisplayDateEnd = DateTime.Now;

            }
            else if (App.user.Type == 3)
            {
                if (Properties.Settings.Default.set_jl_power_time == 0)
                    col1_sp_col1_checkout_record.Visibility = Visibility.Collapsed;

                dp_start_time.DisplayDateStart = DateTime.Now.AddDays(0 - Convert.ToDouble(Properties.Settings.Default.set_jl_power_time));
                dp_start_time.DisplayDateEnd = DateTime.Now;

                dp_end_time.DisplayDateStart = DateTime.Now.AddDays(0 - Convert.ToDouble(Properties.Settings.Default.set_jl_power_time));
                dp_end_time.DisplayDateEnd = DateTime.Now;

            }

            /*if (Properties.Settings.Default.set_refresh_time != 0)
            {
                Timer refreshTabTimer = new Timer(Properties.Settings.Default.set_refresh_time * 1000);
                refreshTabTimer.Enabled = true;
                refreshTabTimer.Elapsed += new System.Timers.ElapsedEventHandler(refreshTabTimer_Elapsed);
                refreshTabTimer.Start();
            }*/
            RefreshCol3();


            txt_uname.Text = user.Uname;
        }

        private void refreshTabTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            this.Dispatcher.BeginInvoke(new System.Threading.ThreadStart(delegate()
            {
                RefreshCol3();
            }));
        }

        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (list_tab != null)
            {
                col2_tab_wp.Children.Clear();

                for (int i = 0; i < list_tab.Count; i++)
                {
                    Order order = list.Find(Order =>
                    {
                        return (Order.Tab_num == list_tab[i].Tab_num && Order.Time != "") || (list_tab[i].Status == 2 && Order.Tab_num == list_tab[i].Tab_num);
                    });

                    if (list_tab[i].Status == 1)  //空闲
                    {
                        StackPanel sp1 = new StackPanel();
                        sp1.Style = Resources["col2_tabone_sp1"] as Style;

                        Border border1 = new Border();
                        border1.Style = Resources["col3_tabone_border"] as Style;
                        border1.Tag = list_tab[i].Tab_num;
                        border1.MouseLeftButtonDown += Tab_LMouseDown;

                        StackPanel sp2 = new StackPanel();
                        sp2.Style = Resources["col2_tabone_sp"] as Style;

                        TextBlock txt_time = new TextBlock();
                        txt_time.Text = "- -";
                        txt_time.Style = Resources["col2_tabone_txt_time"] as Style;

                        TextBlock txt_size = new TextBlock();
                        txt_size.Text = "0/" + list_tab[i].Size;
                        txt_size.Style = Resources["col2_tabone_txt_size"] as Style;
                        txt_size.Foreground = new SolidColorBrush(Colors.Gray);

                        TextBlock txt_uname = new TextBlock();
                        txt_uname.Text = "- -";
                        txt_uname.Style = Resources["col2_tabone_txt_uname"] as Style;

                        TextBlock txt_tabname = new TextBlock();
                        txt_tabname.Text = list_tab[i].Name + "";
                        txt_tabname.Style = Resources["col2_tabone_name"] as Style;

                        Image tab_status = new Image();
                        tab_status.Source = new BitmapImage(new Uri("images/tab_status_xian.png", UriKind.Relative));
                        tab_status.Style = Resources["tab_status_img"] as Style;

                        sp2.Children.Add(txt_time);
                        sp2.Children.Add(txt_size);
                        sp2.Children.Add(txt_uname);

                        border1.Child = sp2;
                        sp1.Children.Add(border1);
                        sp1.Children.Add(tab_status);
                        sp1.Children.Add(txt_tabname);

                        col2_tab_wp.Children.Add(sp1);
                        sp1.Opacity = 0.5;
                    }
                    else if (list_tab[i].Status == 2)   //预定
                    {                     
                        StackPanel sp1 = new StackPanel();
                        sp1.Style = Resources["col2_tabone_sp1"] as Style;

                        Border border1 = new Border();
                        border1.Style = Resources["col3_tabone_border"] as Style;
                        border1.Tag = list_tab[i].Tab_num;
                        border1.MouseLeftButtonDown += Tab_LMouseDown;

                        StackPanel sp2 = new StackPanel();
                        sp2.Style = Resources["col2_tabone_sp"] as Style;

                        TextBlock txt_time = new TextBlock();
                        txt_time.Text = "--";
                        txt_time.Style = Resources["col2_tabone_txt_time"] as Style;

                        TextBlock txt_size = new TextBlock();
                        txt_size.Text = order.Size + "/" + list_tab[i].Size;
                        txt_size.Style = Resources["col2_tabone_txt_size"] as Style;
                        txt_size.Foreground = new SolidColorBrush(Colors.Gray);

                        TextBlock txt_uname = new TextBlock();
                        txt_uname.Text = order.Uname;
                        txt_uname.Style = Resources["col2_tabone_txt_uname"] as Style;

                        TextBlock txt_tabname = new TextBlock();
                        txt_tabname.Text = list_tab[i].Name + "";
                        txt_tabname.Style = Resources["col2_tabone_name"] as Style;

                        Image tab_status = new Image();
                        tab_status.Source = new BitmapImage(new Uri("images/tab_status_ding.png", UriKind.Relative));
                        tab_status.Style = Resources["tab_status_img"] as Style;

                        sp2.Children.Add(txt_time);
                        sp2.Children.Add(txt_size);
                        sp2.Children.Add(txt_uname);

                        border1.Child = sp2;
                        sp1.Children.Add(border1);
                        sp1.Children.Add(tab_status);
                        sp1.Children.Add(txt_tabname);


                        col2_tab_wp.Children.Add(sp1);
                    }
                    else if (list_tab[i].Status == 3)   //使用中
                    {
                        if (order == null && !isAlert)
                        {
                            isAlert = true;
                            string messageBoxText = "桌位编号：" + list_tab[i].Tab_num + "\n数据不一致！\n该桌状态为用餐中，但未找到与之对应的点菜实体！\n\n为了让程序正常运行，是否将该桌状态改为空闲？";
                            string caption = "严重错误";
                            MessageBoxButton button = MessageBoxButton.YesNo;
                            MessageBoxImage icon = MessageBoxImage.Error;
                            MessageBoxResult result = MessageBox.Show(messageBoxText, caption, button, icon);
                            if (result == MessageBoxResult.Yes)
                            {
                                if (App.TabBean.UpdateTabForError(list_tab[i].Tab_num, "1"))
                                {
                                    MessageBox.Show("修复成功！");
                                    Main w = new Main(mUser_num);
                                    this.Close();
                                    w.Show();
                                    return;
                                }
                                else
                                {
                                    MessageBox.Show("修复失败！");
                                }
                            }
                            else
                            {
                                continue;
                            }
                            isAlert = false;
                        }
                        StackPanel sp1 = new StackPanel();
                        sp1.Style = Resources["col2_tabone_sp1"] as Style;

                        Border border1 = new Border();
                        border1.Style = Resources["col3_tabone_border"] as Style;
                        border1.Tag = list_tab[i].Tab_num;
                        border1.MouseLeftButtonDown += Tab_LMouseDown;

                        StackPanel sp2 = new StackPanel();
                        sp2.Style = Resources["col2_tabone_sp"] as Style;

                        TextBlock txt_time = new TextBlock();
                        txt_time.Text = Convert.ToDateTime(order.Time).ToString("HH:mm");
                        txt_time.Style = Resources["col2_tabone_txt_time"] as Style;

                        TextBlock txt_size = new TextBlock();
                        txt_size.Text = order.Size + "/" + list_tab[i].Size;
                        txt_size.Style = Resources["col2_tabone_txt_size"] as Style;
                        txt_size.Foreground = new SolidColorBrush(Colors.Gray);

                        TextBlock txt_uname = new TextBlock();
                        txt_uname.Text = order.Uname;
                        txt_uname.Style = Resources["col2_tabone_txt_uname"] as Style;

                        TextBlock txt_tabname = new TextBlock();
                        txt_tabname.Text = list_tab[i].Name + "";
                        txt_tabname.Style = Resources["col2_tabone_name"] as Style;

                        Image tab_status = new Image();
                        tab_status.Source = new BitmapImage(new Uri("images/tab_status_cai.png", UriKind.Relative));
                        tab_status.Style = Resources["tab_status_img"] as Style;


                        sp2.Children.Add(txt_time);
                        sp2.Children.Add(txt_size);
                        sp2.Children.Add(txt_uname);

                        border1.Child = sp2;
                        sp1.Children.Add(border1);
                        sp1.Children.Add(tab_status);
                        sp1.Children.Add(txt_tabname);


                        col2_tab_wp.Children.Add(sp1);
                    }
                    else if (list_tab[i].Status == 4)   //维修
                    {
                        StackPanel sp1 = new StackPanel();
                        sp1.Style = Resources["col2_tabone_sp1"] as Style;

                        Border border1 = new Border();
                        border1.Style = Resources["col3_tabone_border"] as Style;
                        border1.Tag = list_tab[i].Tab_num;
                        border1.MouseLeftButtonDown += Tab_LMouseDown;
                        ImageBrush img_brush = new ImageBrush();
                        img_brush.ImageSource = new BitmapImage(new Uri(@"pack://application:,,,/images/tab_black.png", UriKind.RelativeOrAbsolute));
                        border1.Background = img_brush;

                        StackPanel sp2 = new StackPanel();
                        sp2.Style = Resources["col2_tabone_sp"] as Style;

                        TextBlock txt_time = new TextBlock();
                        txt_time.Text = "- -";
                        txt_time.Style = Resources["col2_tabone_txt_time"] as Style;

                        TextBlock txt_size = new TextBlock();
                        txt_size.Text = "0/" + list_tab[i].Size;
                        txt_size.Style = Resources["col2_tabone_txt_size"] as Style;
                        txt_size.Foreground = new SolidColorBrush(Colors.Gray);

                        TextBlock txt_uname = new TextBlock();
                        txt_uname.Text = "- -";
                        txt_uname.Style = Resources["col2_tabone_txt_uname"] as Style;

                        TextBlock txt_tabname = new TextBlock();
                        txt_tabname.Text = list_tab[i].Name + "";
                        txt_tabname.Style = Resources["col2_tabone_name"] as Style;

                        Image tab_status = new Image();
                        tab_status.Source = new BitmapImage(new Uri("images/tab_status_xiu.png", UriKind.Relative));
                        tab_status.Style = Resources["tab_status_img"] as Style;

                        sp2.Children.Add(txt_time);
                        sp2.Children.Add(txt_size);
                        sp2.Children.Add(txt_uname);

                        border1.Child = sp2;
                        sp1.Children.Add(border1);
                        sp1.Children.Add(tab_status);
                        sp1.Children.Add(txt_tabname);


                        col2_tab_wp.Children.Add(sp1);
                        sp1.Opacity = 0.5;
                    }
                }
            }
        }

        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            lock (obj)
            {
                //try
                //{
                list = App.OrderBean.GetOrderByTabStatus(0);
                list_tab = App.TabBean.GetTabs();
                // }
                // catch
                // {
                //MessageBox.Show("数据库操作冲突！可能由于桌位状态刷新频率过低导致\n不过不影响整体操作！");
                //  }
            }

        }

        /// <summary>
        /// 单击桌子事件(桌子Tag中保存的是order表的id)
        /// </summary>
        private void Tab_LMouseDown(object sender, MouseButtonEventArgs e)
        {
            int tab_num = Int32.Parse(((Border)sender).Tag.ToString());
            mTrue_tab_num = tab_num;
            mTrue_tab_name = App.TabBean.GetTabByField("tab_num", tab_num + "").Name;
            if (tab_num < 0)
            {
                gd_checkout_left.Visibility = Visibility.Collapsed;
            }
            else
            {
                List<Order> list = App.OrderBean.GetUncheckedOrderByTabNum(tab_num);
                if (list.Count > 0)
                {
                    tc_tabs.Items.Clear();
                    TabItem tabItem = new TabItem();
                    tabItem.Tag = mTrue_tab_num;
                    tabItem.Header = mTrue_tab_name;
                    tc_tabs.Items.Add(tabItem);
                    lb_dingtime.Visibility = Visibility.Visible;
                    lb_dingtime.ItemsSource = list;
                    lb_dingtime.SelectedIndex = 0;

                    gd_checkout_left.Visibility = Visibility.Visible;
                }
                else
                {
                    gd_checkout_left.Visibility = Visibility.Collapsed;
                }


                //dg_orders_binding(order_id);
            }
        }

        /// <summary>
        /// 根据订单id显示订单详情
        /// </summary>
        /// <param name="order_id">order_id</param>
        private void dg_orders_binding(string tOrder_id)
        {
            order_id = tOrder_id;
            Order order = App.OrderBean.GetOrderById(Int32.Parse(tOrder_id));

            if (order.Together_name != "")
            {
                txt_tg_info.Text = "套餐" + order.Together_name + "(" + App.TogetherBean.GetTogetherByField("name", order.Together_name).Price + "元)";
                DataTable tg_table = App.TogetherBean.GetOrdersByName(order.Together_name);
                dg_tg_orders.ItemsSource = tg_table.DefaultView;
                dg_tg_orders.Visibility = Visibility.Visible;
            }
            else
            {
                dg_tg_orders.Visibility = Visibility.Collapsed;
                dg_tg_orders.ItemsSource = null;
                txt_tg_info.Text = "";
            }

            txt_order_num.Text = "No." + order.Order_num;
            txt_tab_namenum.Text = order.Tab_name;
            txt_size.Text = order.Size + "";

            if (order.Type == 2 && order.Time == "")
            {
                sp_col2_btm.Visibility = Visibility.Hidden;
            }
            else
            {
                sp_col2_btm.Visibility = Visibility.Visible;
            }

            DataTable table = App.OrdersBean.GetOrdersDataTableByOrderNum(order.Order_num);
            if (table.Rows.Count > 0)
            {
                dg_orders.Visibility = Visibility.Visible;
            }
            else
            {
                dg_orders.Visibility = Visibility.Collapsed;
            }
            dg_orders.ItemsSource = table.DefaultView;
            table = App.OrdersBean.GetReturnedOrdersDataTableByOrderNum(order.Order_num);
            if (table.Rows.Count > 0)
                sp_returned.Visibility = Visibility.Visible;
            else
                sp_returned.Visibility = Visibility.Collapsed;
            dg_returnedorders.ItemsSource = table.DefaultView;
        }

        private void lb_dingtime_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Order order = (Order)((ListBox)sender).SelectedItem;


            if (order != null)
            {
                mNow_order_num = order.Order_num;

                dg_orders_binding(order.Id + "");
                if (order.Type == 2 && order.Time == "")
                {
                    btn_del_yd.Visibility = Visibility.Visible;
                    btn_del_yd.Tag = order.Order_num;
                }
                else
                {
                    btn_del_yd.Visibility = Visibility.Collapsed;
                }
            }
        }


        /// <summary>
        /// 单击收银事件
        /// </summary>
        private void col1_sp_cash_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //gd_checkout_left.Visibility = Visibility.Visible;
            gd_checkout_right.Visibility = Visibility.Visible;
            gd_statistic_left.Visibility = Visibility.Collapsed;
            gd_statistic_right.Visibility = Visibility.Collapsed;
            RefreshCol3();
        }


        /// <summary>
        /// 刷新桌子状态（Tag：-1空闲-2预订-4维修）
        /// </summary>
        public void RefreshCol3()
        {
            BackgroundWorker bw = new BackgroundWorker();
            bw.DoWork += bw_DoWork;    //调用RunWorkerAsync()时发生 所以放在前面
            bw.RunWorkerAsync();
            bw.RunWorkerCompleted += bw_RunWorkerCompleted;
        }


        private void dg_orders_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.Header = e.Row.GetIndex() + 1;
        }

        /// <summary>
        /// 结账按钮
        /// </summary>
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            List<int> t_list_tab_num = new List<int>();
            foreach (TabItem item in tc_tabs.Items)
            {
                t_list_tab_num.Add(Int32.Parse(item.Tag.ToString()));
            }
            CheckOutDlg checkOut = new CheckOutDlg(order_id, t_list_tab_num);
            //CheckOutDlg checkOut = new CheckOutDlg("2");

            if (checkOut.ShowDialog() == true)
            {
                RefreshCol3();
                gd_checkout_left.Visibility = Visibility.Collapsed;
            }
        }
        /// <summary>
        /// 设置按钮
        /// </summary>
        private void col1_sp_set_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            SetDlg setDlg = new SetDlg();
            setDlg.ShowDialog();
        }

        /// <summary>
        /// 管理
        /// </summary>
        private void col1_sp_manage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            ManageDlg manageDlg = new ManageDlg(); ;
            manageDlg.ShowDialog();
        }

        private void Image_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
        {
            MessageBox.Show("敬请期待！");
        }

        private void Image_MouseLeftButtonDown_2(object sender, MouseButtonEventArgs e)
        {
            string messageBoxText = "确认注销吗？";
            string caption = "注销";
            MessageBoxButton button = MessageBoxButton.YesNo;
            MessageBoxImage icon = MessageBoxImage.Warning;
            MessageBoxResult result = MessageBox.Show(messageBoxText, caption, button, icon);
            if (result == MessageBoxResult.Yes)
            {
                Login login = new Login();
                login.ShowDialog();
                this.Close();
            }
        }

        private void col1_sp_col1_checkout_record_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
        {
            gd_checkout_left.Visibility = Visibility.Collapsed;
            gd_checkout_right.Visibility = Visibility.Collapsed;
            //gd_statistic_left.Visibility = Visibility.Visible;
            gd_statistic_right.Visibility = Visibility.Visible;
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            
            string stime = dp_start_time.Text;
            string etime = "";
            if(dp_end_time.Text!=""){
                etime = DateTime.Parse(dp_end_time.Text).AddDays(1).ToString();
            }

            string where_pre;
            if (stime != "")
            {
                if (etime != "")
                {
                    where_pre = "time between '" + stime + "' and '" + etime + "'";
                    print_tip = "时间：" + stime + "至" + etime;
                }
                else
                {
                    where_pre = "time >='" + stime + "'";
                    print_tip = "时间：" + stime + "至今";
                }
            }
            else
            {
                if (App.user.Type != 4)
                {
                    MessageBox.Show("请选择开始时间！");
                    return;
                }
                if (etime != "")
                {
                    where_pre = "time<='" + etime + "'";
                    print_tip = "时间：开始至" + etime;
                }
                else
                {
                    MessageBox.Show("时间范围填写错误!至少要填写一个");
                    return;
                }
            }
            gd_statistic_left.Visibility = Visibility.Visible;
            mWhere_pre = where_pre;
            if (statistic_type.SelectedIndex == 0) {
                tc_statistic.Visibility = Visibility.Visible;
                dg_statistic_tg.Visibility = Visibility.Collapsed;
                tb_statistic_title.Text = "账单汇总";
                btn_hz.Visibility = Visibility.Visible;

                mStartIndex = 0;   //必须加上，不然mStartIndex是全局变量，下面有可能取不到数据
                dg_statistic_detail.ItemsSource = App.StatisticBean.GetDetail(where_pre, (mStartIndex) * mPageNums, mPageNums).DefaultView;

                txt_print_tip.Text = print_tip;

                string zc_start = "08:00:00";   //中餐开始时间
                string zc_end = "16:00:00";     //.....结束..

                //划分中晚餐
                txt_hascheckouted_num.Text = App.StatisticBean.GetCheckOutedNum(where_pre) + "";
                string hascheckouted_num_zc = App.StatisticBean.GetCheckOutedNum(where_pre + " and substring(time,12)>='" + zc_start + "' and substring(time,12)<'" + zc_end + "'") + "";
                int hascheckouted_num_wc = Int32.Parse(txt_hascheckouted_num.Text) - Int32.Parse(hascheckouted_num_zc);
                tb_hascheckouted_num.Text = "已结帐单数(中:" + hascheckouted_num_zc + "|晚:" + hascheckouted_num_wc + ")";

                //划分中晚餐
                txt_hascheckouted_sum.Text = App.StatisticBean.GetCheckOutedSum("sum", where_pre) + "";
                float hascheckouted_sum_zc = App.StatisticBean.GetCheckOutedSum("sum", where_pre + " and substring(time,12)>='" + zc_start + "' and substring(time,12)<'" + zc_end + "'");
                float hascheckouted_sum_wc = float.Parse(txt_hascheckouted_sum.Text) - hascheckouted_sum_zc;
                tb_hascheckouted_sum.Text = "已结帐金额(中:" + hascheckouted_sum_zc + "|晚:" + hascheckouted_sum_wc + ")";

                float hasnotcheckout_sum = App.StatisticBean.GetNotCheckOutedSum(where_pre);
                txt_notcheckouted_sum.Text = hasnotcheckout_sum + "";
                txt_notcheckouted_num.Text = "未结帐金额(单数："+App.StatisticBean.GetNotCheckOutedNum(where_pre) + ")";

                txt_gz_sum.Text = App.StatisticBean.GetGzSum(where_pre) + "";
                float cash_sum = App.StatisticBean.GetCheckOutedSum("cash_sum", where_pre);
                txt_cash_sum.Text = cash_sum + "";
                float djq_sum = App.StatisticBean.GetCheckOutedSum("djq_sum", where_pre);
                txt_djq_sum.Text = djq_sum + "";
                float tgq_sum = App.StatisticBean.GetCheckOutedSum("tgq_sum", where_pre);
                txt_tgq_sum.Text = tgq_sum + "";
                float xyk_sum = App.StatisticBean.GetCheckOutedSum("xyk_sum", where_pre);
                txt_xyk_sum.Text = xyk_sum + "";
                float hyk_sum = App.StatisticBean.GetCheckOutedSum("hyk_sum", where_pre);
                txt_hyk_sum.Text = hyk_sum + "";
                txt_pc_sum.Text = App.StatisticBean.GetCheckOutedSum("pc_sum", where_pre) + "";
                txt_tg_nums.Text = App.StatisticBean.GetHisTgNum(where_pre) + "";

                float tg_sum = App.StatisticBean.GetHisTgSum(where_pre);
                txt_tg_sum.Text = tg_sum + "";
                float tg_sum_zc = App.StatisticBean.GetHisTgSum(where_pre + " and substring(time,12)>='" + zc_start + "' and substring(time,12)<'" + zc_end + "'");
                float tg_sum_wc = float.Parse(txt_tg_sum.Text) - tg_sum_zc;

                txt_returned.Text = App.StatisticBean.GetHisReturnedSum(where_pre) + "";
                txt_returned_drink.Text = App.StatisticBean.GetHisReturnedSum(where_pre + " and (type like '%酒%' or type like '%饮%')") + "";
                float returned_drink_1 = App.StatisticBean.GetHisReturnedSum(where_pre + " and type like '%酒%'");
                float returned_drink_2 = float.Parse(txt_returned_drink.Text) - returned_drink_1;
                tb_returned_drink.Text = "--| 酒饮(酒:" + returned_drink_1 + "|饮:" + returned_drink_2 + ")";
                txt_returned_food.Text = (float.Parse(txt_returned.Text) - float.Parse(txt_returned_drink.Text)) + "";


                // txt_sum.Text = (float.Parse(txt_gz_sum.Text) + float.Parse(txt_cq_sum.Text) + float.Parse(txt_xyk_sum.Text) + float.Parse(txt_cash_sum.Text)) + "";
                txt_sum.Text = (App.StatisticBean.GetCheckOutedSum("sum", where_pre) + float.Parse(txt_tg_sum.Text))+ "";
                    txt_sum_food.Text = App.StatisticBean.GetCheckOutedSum("food_sum", where_pre) + "";
                    txt_sum_drink.Text = App.StatisticBean.GetCheckOutedSum("drink_sum", where_pre) + "";
                    float drink_1 = App.StatisticBean.GetHisOrdersSum(where_pre + " and dhs.type like '%酒%'") - returned_drink_1;   //drink_sum已经减去退菜的了，这里也要减去
                    float drink_2 = float.Parse(txt_sum_drink.Text) - drink_1;
                    tb_sum_drink.Text = "--| 酒饮(酒:" + drink_1 + "|饮:"+drink_2+")";
                //划分中晚餐
                    float sum_zc = App.StatisticBean.GetCheckOutedSum("sum", where_pre + " and substring(time,12)>='" + zc_start + "' and substring(time,12)<'" + zc_end + "'") + tg_sum_zc;
                    float sum_wc = float.Parse(txt_sum.Text) - sum_zc;
                tb_sum.Text = "折前应收(中:" + sum_zc + "|晚:" + sum_wc + ")";


                //txt_final_cash.Text = (App.StatisticBean.GetFinalSum(where_pre) + float.Parse(txt_tg_sum.Text)) + "";    //这样会把代金券未使用的部分也计算进去
                txt_final_cash.Text = cash_sum + djq_sum + tgq_sum + xyk_sum + hyk_sum + tg_sum + "";   
                //划分中晚餐
                //float final_cash_zc = App.StatisticBean.GetFinalSum(where_pre + " and substring(time,12)>='" + zc_start + "' and substring(time,12)<'" + zc_end + "'") + tg_sum_zc;
                //float final_cash_wc = float.Parse(txt_final_cash.Text) - final_cash_zc;
                tb_final_cash.Text = "折后实收";


                txt_sub_sum.Text = App.StatisticBean.GetSubSum(where_pre) + "";
                //划分中晚餐
                float sub_sum_zc = App.StatisticBean.GetSubSum(where_pre + " and substring(time,12)>='" + zc_start + "' and substring(time,12)<'" + zc_end + "'");
                float sub_sum_wc = float.Parse(txt_sub_sum.Text) - sub_sum_zc;
                tb_sub_sum.Text = "优惠(中:" + sub_sum_zc + "|晚:" + sub_sum_wc + ")";


               
            }
            else if (statistic_type.SelectedIndex == 1)
            {
                tc_statistic.Visibility = Visibility.Collapsed;
                dg_statistic_tg.Visibility = Visibility.Visible;
                tb_statistic_title.Text = "团购汇总";
                btn_hz.Visibility = Visibility.Collapsed;

                DataTable tg_table = App.StatisticBean.GetHisAllTgInfo(where_pre);
                dg_statistic_tg.ItemsSource = tg_table.DefaultView;
            }
        }

        private void col1_sp_order_yd_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
        {
            OrderYdDlg ydDlg = new OrderYdDlg();
            ydDlg.ShowDialog();
        }

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            PrintUtil printUtil = new PrintUtil();
            int print_blocks = 14;
            //printUtil.UsbPrintStringTitle("　　账单汇总");
            StringUtil strUtil = new StringUtil();
            string str = "　　　　　　"+"账单汇总\n";
            str += print_tip + "\n";
            str += strUtil.FillStr(tb_hascheckouted_num.Text, print_blocks-2, "　") + txt_hascheckouted_num.Text + "\n";
            str += strUtil.FillStr(tb_hascheckouted_sum.Text, print_blocks-2, "　") + txt_hascheckouted_sum.Text + "\n";
            str += strUtil.FillStr(txt_notcheckouted_num.Text, print_blocks, "　") + txt_notcheckouted_sum.Text + "\n";
            str += "------------------------------------------\n";
            str += strUtil.FillStr("挂账", print_blocks, "　") + txt_gz_sum.Text + "\n";
            str += strUtil.FillStr("现金", print_blocks, "　") + txt_cash_sum.Text + "\n";
            str += strUtil.FillStr("代金券", print_blocks, "　") + txt_djq_sum.Text + "\n";
            str += strUtil.FillStr("团购券", print_blocks, "　") + txt_tgq_sum.Text + "\n";
            str += strUtil.FillStr("银行POS", print_blocks+1, "　") + txt_xyk_sum.Text + "\n";
            str += strUtil.FillStr("会员卡", print_blocks, "　") + txt_hyk_sum.Text + "\n";
            str += strUtil.FillStr("已售团购套餐数", print_blocks, "　") + txt_tg_nums.Text + "\n";
            str += strUtil.FillStr("已售团购套餐总额", print_blocks, "　") + txt_tg_sum.Text + "\n";
            str += "------------------------------------------\n";
            str += strUtil.FillStr("退菜", print_blocks, "　") + txt_returned.Text + "\n";
            str += strUtil.FillStr(tb_returned_food.Text, print_blocks + 2, "　") + txt_returned_food.Text + "\n";
            str += strUtil.FillStr(tb_returned_drink.Text, print_blocks + 2, "　") + txt_returned_drink.Text + "\n";
            str += "------------------------------------------\n";
            str += strUtil.FillStr(tb_sum.Text, print_blocks-2, "　") + txt_sum.Text + "\n";
            str += strUtil.FillStr(tb_sum_food.Text, print_blocks+2, "　") + txt_sum_food.Text + "\n";
            str += strUtil.FillStr(tb_sum_drink.Text, print_blocks+2, "　") + txt_sum_drink.Text + "\n";
            str += strUtil.FillStr("赔偿", print_blocks, "　") + txt_pc_sum.Text + "\n";
            str += strUtil.FillStr(tb_final_cash.Text, print_blocks-2, "　") + txt_final_cash.Text + "\n";
            str += strUtil.FillStr(tb_sub_sum.Text, print_blocks-2, "　") + txt_sub_sum.Text + "\n";
            
           MessageBox.Show(str);
            printUtil.UsbPrintString(str + "\n.\n.\n.\n");
        }

        private void btn_cos_Click(object sender, RoutedEventArgs e)
        {
            CosSelDlg dlg = new CosSelDlg(list_tab_num);
            dlg.ShowDialog();
            foreach (int i in list_tab_num)
            {
                TabItem item = new TabItem();
                item.Tag = i;
                item.Header = App.TabBean.GetTabByField("tab_num", i + "").Name + "";
                bool flag = true;
                for (int j = 0; j < tc_tabs.Items.Count; j++)
                {
                    if (((TabItem)tc_tabs.Items[j]).Tag.ToString() == (i + ""))
                        flag = false;
                }
                if (flag)
                    tc_tabs.Items.Add(item);
            }
        }


        private void tc_tabs_GotFocus(object sender, RoutedEventArgs e)
        {
            string tab_name = ((TabItem)tc_tabs.SelectedItem).Header.ToString();
            int now_order_id = App.OrderBean.GetNowOrderIdByTabNum(App.TabBean.GetTabsByField("name", tab_name)[0].Tab_num);
            dg_orders_binding(now_order_id + "");
            if (mTrue_tab_name != tab_name)
            {
                sp_col2_btm.Visibility = Visibility.Collapsed;
            }
            else
            {
                sp_col2_btm.Visibility = Visibility.Visible;
            }
        }

        private void btn_del_yd_Click(object sender, RoutedEventArgs e)
        {
            string messageBoxText = "确认取消当前预定吗？";
            string caption = "取消预定";
            MessageBoxButton button = MessageBoxButton.YesNo;
            MessageBoxImage icon = MessageBoxImage.Warning;
            MessageBoxResult result = MessageBox.Show(messageBoxText, caption, button, icon);
            if (result == MessageBoxResult.Yes)
            {
                if (App.OrderBean.DelOrderByOrderNum(btn_del_yd.Tag.ToString(), App.OrderBean.GetOrderByOrderNum(btn_del_yd.Tag.ToString()).Tab_num))
                {
                    MessageBox.Show("取消成功！");
                    gd_checkout_left.Visibility = Visibility.Collapsed;
                }
                else
                {
                    MessageBox.Show("取消失败！");
                }
            }
        }

        private void btn_add_orders_Click(object sender, RoutedEventArgs e)
        {
            OrdersAddDlg oad = new OrdersAddDlg(mNow_order_num);
            oad.ShowDialog();
            if (oad.DialogResult == true)
            {
                gd_checkout_left.Visibility = Visibility.Collapsed;
            }
        }

        private void btn_hurry_Click(object sender, RoutedEventArgs e)
        {
            string result = "";
            try
            {
                PostSubmitter postSub = new PostSubmitter();
                result = postSub.SimplePost("{\"tabname\":\"" + mTrue_tab_name + "\"}", "http://localhost:8080/OrderSystemServlet/HarryOrderServlet");
            }
            catch
            {
                MessageBox.Show("与服务器通讯发生错误！");
                return;
            }
            MessageBox.Show("已经催菜！");
            return;

        }

        private void TabControl_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            if (tc_statistic.SelectedIndex == 0)
            {
                btn_hz.Visibility = Visibility.Visible;
                sp_mx.Visibility = Visibility.Collapsed;
            }
            else
            {
                btn_hz.Visibility = Visibility.Collapsed;
                sp_mx.Visibility = Visibility.Visible;
            }
        }

        private void Button_Click_4(object sender, RoutedEventArgs e)
        {
            DataRowView SelectedElement = (DataRowView)dg_statistic_detail.SelectedItem;
            if (SelectedElement == null)
            {
                MessageBox.Show("请选择一个帐单!");
                return;
            }
            string result = SelectedElement.Row[12].ToString();
            string checkout_num = SelectedElement.Row[11].ToString();
            ShowOrderDetailDlg dlg = new ShowOrderDetailDlg(result, checkout_num);
            dlg.ShowDialog();
        }

        private void btn_nextpage_Click(object sender, RoutedEventArgs e)
        {
            if (App.StatisticBean.GetDetail(mWhere_pre, (mStartIndex + 1) * mPageNums, mPageNums).Rows.Count>0)
            {
                mStartIndex++;
                dg_statistic_detail.ItemsSource = App.StatisticBean.GetDetail(mWhere_pre, (mStartIndex) * mPageNums, mPageNums).DefaultView;
            }
        }

        private void btn_prepage_Click(object sender, RoutedEventArgs e)
        {
            if (mStartIndex - 1 >= 0) { 
                mStartIndex--;
                dg_statistic_detail.ItemsSource = App.StatisticBean.GetDetail(mWhere_pre, (mStartIndex) * mPageNums, mPageNums).DefaultView;
            }
        }

        //Order
        private void col1_sp_order_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            OrderDlg dlg = new OrderDlg();
            dlg.ShowDialog();
        }
    }
}
